package demo

import (
	"bytes"
	"encoding/binary"
	"log"
	"math"
	"os"

	"gitee.com/general252/ebml-go/core"
	"gitee.com/general252/ebml-go/mkv"
	"gitee.com/general252/ebml-go/mkvcore"
	"gitee.com/general252/ebml-go/webm"
	"gitee.com/general252/go-wav"
)

func G726Demo() {
	inputFilename := "output.g726"
	outFilename := "outG726.mkv"

	fp, err := os.Open(inputFilename)
	if err != nil {
		return
	} else {
		defer fp.Close()
	}

	w, err := os.OpenFile(outFilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		log.Println(err)
		return
	} else {
		defer w.Close()
	}

	// FFmpeg-n4.4/libavformat/matroskadec.c/"A_MS/ACM"(ff_get_wav_header)
	wavFormat := wav.WavFormat{
		AudioFormat:   0x45, // wav.AudioFormatALaw
		NumChannels:   1,
		SampleRate:    8000,
		ByteRate:      4000,
		BlockAlign:    1,
		BitsPerSample: 4,
	}

	var codecPrivate bytes.Buffer
	binary.Write(&codecPrivate, binary.LittleEndian, wavFormat)

	ws, err := webm.NewSimpleBlockWriter(w,
		[]*webm.TrackEntry{
			{
				Name:         "Audio",
				TrackNumber:  1,
				TrackUID:     12345,
				CodecID:      core.AudioCodecMSACM,
				TrackType:    core.TrackTypeAudio,
				CodecPrivate: codecPrivate.Bytes(),
				Audio: &webm.Audio{
					SamplingFrequency: float64(wavFormat.SampleRate),
					Channels:          uint64(wavFormat.NumChannels),
				},
			},
		},
		mkvcore.WithSeekHead(true),
		mkvcore.WithCues(true),
		mkvcore.WithEBMLHeader(mkv.DefaultEBMLHeader),
		mkvcore.WithSegmentInfo(mkv.DefaultSegmentInfo),
		mkvcore.WithMaxKeyframeInterval(1, math.MaxInt16-5000),
	)

	if err != nil {
		log.Println(err)
		return
	} else {
		defer ws[0].Close()
	}

	audioStream := ws[0]

	var timestamp int64

	for {
		buff := make([]byte, 160)
		n, err := fp.Read(buff)
		if err != nil {
			break
		}

		_, _ = audioStream.Write(true, timestamp, buff[:n])
		timestamp += 40
	}
}
